<template>
  <div class="app-container">
    <!-- 搜索框 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input v-model="queryParams.keywords" placeholder="请输入关键字" clearable style="width: 200px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" :icon="Search">搜索</el-button>
          <el-button type="info" @click="resetQuery">
            重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between">
          <div>
            <el-button type="success" @click="openDialog()">新增</el-button>
            <el-button type="danger" :disabled="ids.length === 0" @click="handleDelete()"><i-ep-delete />批量删除</el-button>
          </div>
          <!-- 导入导出 -->
          <div>
            <el-dropdown split-button>
              导入
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="downloadTemplate">
                    <i-ep-download />下载模板</el-dropdown-item>
                  <el-dropdown-item @click="()=>{importDialogVisible = true}">
                    <i-ep-top />导入数据</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button class="ml-3" @click="handleUserExport"><template><i-ep-download /></template>导出</el-button>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="keywordList" @selection-change="handleSelectionChange" border stripe
        style="width: 100%" highlight-current-row>
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="序号" width="150" align="center">
          <template #default="{ $index }">
            {{ (queryParams.page - 1) * queryParams.limit + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" width="300" header-align="center" align="center" label="关键词名称">
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="primary" round plain @click="openDialog(scope.row.id)"><i-ep-edit />编辑</el-button>
            <el-button type="danger" round plain @click="handleDelete(scope.row.id)"><i-ep-delete />删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination v-if="total > 0" :page-sizes="[5, 10, 15, 20]" v-model:total="total" v-model:page="queryParams.page"
        v-model:limit="queryParams.limit" @pagination="handleQuery" @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle" layout="total, sizes, prev, pager, next, jumper" />
    </el-card>

    <!-- 导入弹窗 -->
     <!-- 导入弹窗 -->
     <el-dialog
      v-model="importDialogVisible"
      title="批量导入关键词"
      width="600px"
      append-to-body
      @close="closeImportDialog"
    >
      <el-form label-width="80px">
        <el-form-item label="Excel">
          <el-upload
            class="upload-demo"
            action=""
            drag
            :auto-upload="false"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
            :file-list="excelFilelist"
            :on-change="handleExcelChange"
            :limit="1"
          >
            <el-icon class="el-icon--upload">
              <upload-filled />
            </el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">xls/xlsx files</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleKeywordImport">确 定</el-button>
          <el-button @click="closeImportDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 表单弹窗 -->
    <el-dialog v-model="dialogFormVisible" :title="dialogType" width="600px" append-to-body @close="closeDialog">
      <el-form ref="keywordFormRef" :model="formData" :rules="rules" label-width="120px">
        <el-form-item label="关键词名称" prop="name">
          <el-input v-model="formData.name" placeholder="关键词名称"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Search,UploadFilled } from '@element-plus/icons-vue'
import {
  getListApi,
  getInfoApi,
  deleteApi,
  saveApi,
  updateApi,
  downloadTemplateApi,
  exportKeywordApi,
  importKeywordApi,
} from "@/api/qualityInspect/keyword.js";
import { reactive, ref } from "vue";
import {
  ElForm,
  ElInput,
  ElMessage,
  ElMessageBox,
  ElTable,
UploadFile,
} from 'element-plus'

// 分页查询参数接口
interface KeywordQuery {
  keywords?: string;
  page?: number;
  limit?: number;
}

// 列表接口
interface KeywordPageVO {
  id?: number;
  name?: string;
  gsid?: string;
}


// 添加修改表单数据接口
interface KeywordForm {
  id?: number;
  name?: string;
}
const excelFile = ref<File>();
const excelFilelist = ref<File[]>([]);
const queryFormRef = ref(ElForm); // 查询表单
const keywordFormRef = ref(ElForm); 

const loading = ref(false);
const ids = ref([]); // 被选中的id集合
const total = ref(0);
const dialogFormVisible = ref(false)
const dialogType = ref('')
const importDialogVisible = ref(false)
const queryParams = reactive<KeywordQuery>({
  page: 1,
  limit: 10,
});

const keywordList = ref<KeywordPageVO[]>();

const formData = reactive<KeywordForm>({});

const rules = reactive({
  name: [
    { required: true, message: '关键词名称不能为空', trigger: 'blur' }
  ]
});

/**
 * 导入关键词
 */
 function handleKeywordImport() {
    if (!excelFile.value) {
      ElMessage.warning("上传Excel文件不能为空");
      return false;
    }
    importKeywordApi(excelFile.value).then(({data}) => {
      ElMessage({
        duration:10000,
        showClose: true,    
        dangerouslyUseHTMLString: true,
        message: data,
        type:'success'
      });
      closeImportDialog();
      resetQuery();
    });
}

/**
 * 关闭导入弹窗
 */
 function closeImportDialog() {
  importDialogVisible.value = false;
  excelFile.value = undefined;
  excelFilelist.value = [];
}


/**
 * Excel文件change事件
 *
 * @param file
 */
 function handleExcelChange(file: UploadFile) {
  if (!/\.(xlsx|xls|XLSX|XLS)$/.test(file.name)) {
    ElMessage.warning("上传Excel只能为xlsx、xls格式");
    excelFile.value = undefined;
    excelFilelist.value = [];
    return false;
  }
  excelFile.value = file.raw;
}

/**
 * 下载导入模板
 */
 const downloadTemplate = ()=>{
  downloadTemplateApi().then((response) => {
    const blob = new Blob([response.data]);
    console.log(response)
    /* const blob = new Blob([response.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
    }); */
    const a = document.createElement("a");
    const href = window.URL.createObjectURL(blob); // 下载链接
    a.href = href;
    a.download = decodeURI(
      response.headers["content-disposition"].split(";")[1].split("=")[1]
    ); // 获取后台设置的文件名称
    document.body.appendChild(a);
    a.click(); // 点击下载
    document.body.removeChild(a); // 下载完成移除元素
    window.URL.revokeObjectURL(href); // 释放掉blob对象
  });
}


/**
 * 导出关键词
 */
 const handleUserExport = () =>{

  // 确认
  ElMessageBox.confirm(`确认导出全部${total.value}条记录?`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    exportKeywordApi(queryParams).then((response: any) => {
    const blob = new Blob([response.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
    });
    const a = document.createElement("a");
    const href = window.URL.createObjectURL(blob); // 下载的链接
    a.href = href;
    a.download = decodeURI(
      response.headers["content-disposition"].split(";")[1].split("=")[1]
    ); // 获取后台设置的文件名称
    document.body.appendChild(a);
    a.click(); // 点击导出
    document.body.removeChild(a); // 下载完成移除元素
    window.URL.revokeObjectURL(href); // 释放掉blob对象
  });
  });

  
}


/**
 * 查询
 */
const handleQuery = () => {
  loading.value = true;
  getListApi(queryParams) // 获取列表
    .then(({ data }) => {
      keywordList.value = data.list;
      total.value = data.totalCount;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 重置查询
 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  queryParams.page = 1;
  handleQuery();
}

/**
 * 修改每页数
 */
const sizeChangeHandle = (val: number) => {
  queryParams.limit = val
  queryParams.page = 1
  handleQuery()
}

/**
 * 修改当前页
 */
const currentChangeHandle = (val: number) => {
  queryParams.page = val
  handleQuery()
}

/**
 * 行checkbox change事件
 */
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.id);
}


/**
 * 打开添加修改弹窗
 */
const openDialog = (idId?: number) => {

  dialogFormVisible.value = true;
  if (idId) {
    dialogType.value = "修改";
    getInfoApi(idId).then(({ data }) => {
      Object.assign(formData, data);
    });
  } else {
    dialogType.value = "新增";
  }
}

/**
 * 关闭弹窗
 */
const closeDialog = () => {
  dialogFormVisible.value = false;
  resetForm();
}

/**
 * 重置表单
 */
const resetForm = () => {
  keywordFormRef.value.resetFields();
  keywordFormRef.value.clearValidate();

  formData.id = undefined;

}

/**
 * 表单提交
 */
const handleSubmit = () => {
  keywordFormRef.value.validate((valid: any) => {
    if (valid) {
      const keywordId = formData.id;
      loading.value = true;

      // 更新操作
      if (keywordId) {
        updateApi(formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        saveApi(formData) // 添加操作
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/**
 * 删除记录
 */
const handleDelete = (id?: number) => {
  let keywordIds = []
  // 单个删除
  if (id != null) {
    keywordIds.push(id)
  } else {
    // 批量删除
    if (!ids) {
      ElMessage.warning("请勾选删除项");
      return;
    }
    keywordIds = ids.value
  }


  ElMessageBox.confirm("确认删除选中的记录?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteApi(keywordIds).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}


handleQuery(); // 初始化列表数据

</script>
